#ifndef __TCP_SERVER_HPP__
#define __TCP_SERVER_HPP__

#include <string>
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <functional>
#include <cstdlib>
#include <unistd.h>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Thread.hpp"
#include "Comm.hpp"
#include "ThreadPool.hpp"
using namespace std;
using namespace LogModule;
using namespace ThreadModlue;
using namespace ThreadPoolModule;
using task_t = function<void()>;

static const int default_listen_sockfd = -1;
static const int gback = 8;
static const uint16_t defaultport = 8080;

class TcpServer
{
private:
    void HandlerIO(int sockfd, InetAddr client)
    {
        char buffer[1024];
        while (true)
        {
            buffer[0] = 0;
            ssize_t n = read(sockfd, &buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                string echo_client;
                cout << "Client echo# " << buffer << endl;
                echo_client += buffer;
                write(sockfd, echo_client.c_str(), echo_client.size());
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "客户端退出 :" << client.Tostring();
                break;
            }
            else
            {
                LOG(LogLevel::FATAL) << "read error";
                break;
            }
        }
        close(sockfd);
    }

public:
    TcpServer(uint16_t port = defaultport)
        : _port(port),
          _listensockfd(default_listen_sockfd)
    {
    }

    void Init()
    {
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket create error";
            exit(SOCKET_CREATE_ERR);
        }
        LOG(LogLevel::INFO) << "socket success create";

        InetAddr _local(_port);

        if (bind(_listensockfd, _local.Addr(), _local.Length()) != 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(SOCKET_BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";

        if (listen(_listensockfd, gback) != 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            exit(SOCKET_LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success";
    }

    class ThreadData
    {
    public:
        ThreadData(int sockfd,TcpServer *self,const InetAddr &addr)
        :_self(self),
        _sockfd(sockfd),
        _addr(addr)
        {
        }

    public:
        TcpServer *_self;
        int _sockfd;
        InetAddr _addr;
    };

    static void *Routine(void *argv)
    {
        ThreadData* td = static_cast<ThreadData*>(argv);
        pthread_detach(pthread_self());
        td->_self->HandlerIO(td->_sockfd,td->_addr);
        delete td;

        return nullptr;
    }

    void Start()
    {
        //方法三分支：
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd,(sockaddr*)&peer,&len);
            if(sockfd<0)
            {
                LOG(LogLevel::FATAL)<<"accept error";
                exit(SOCKET_ACCEPT_ERR);
            }
            InetAddr ChildAddr(peer);
            LOG(LogLevel::INFO)<<"accept success"<<ChildAddr.Tostring();

            // 方法一：直接进行调用函数
            //HandlerIO(sockfd,ChildAddr);

            // 方法二：创建线程执行
            //pthread_t tid;
            //ThreadData *td = new ThreadData(sockfd,this,ChildAddr);
            //pthread_create(&tid,nullptr,Routine,(void*)td);

            //方法三：进程执行
            // 创建子进程，子进程创建孙子进程，目的是为了将任务脱离出去不要和父进程进行强绑定
            // 需要注意，fork后会继承下父进程的资源，需要进行相应的关闭资源
            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::FATAL)<<"创建子进程失败";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                close(_listensockfd);
                if(fork()>0)
                    exit(OK);
                HandlerIO(sockfd,ChildAddr);
                exit(OK);
            }
            else
            {
                close(sockfd);
                pid_t wid = waitpid(id,nullptr,0);
            }
            //方法四：创建线程池执行
            ThreadPool<task_t>::GetInstance()->Enqueue([this,sockfd,ChildAddr](){
                this->HandlerIO(sockfd,ChildAddr);
            });
        }
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensockfd;
};

#endif